'use client'

import {
	Accordion,
	AccordionDetails,
	AccordionSummary,
	Skeleton,
	Typography
} from '@mui/material'
import Box from '@mui/material/Box'
import { useQuery } from '@tanstack/react-query'
import { ChevronDown, SearchX } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { toast } from 'sonner'

import { AttachGallery } from '@/components/AttachGallery'
import { TasksGallery } from '@/components/TasksGallery'
import { ClientMinCard } from '@/components/cards/min/client.min.card'
import { RequestCard } from '@/components/cards/request.card'

import { clientService } from '@/services/clients.service'
import { requestService } from '@/services/requests.service'

export function RequestDetail({ id }: { id: string }) {
	const req_id = Number(id)
	const { data, isError, error, fetchStatus, status } = useQuery({
		queryKey: ['request', req_id],
		queryFn: async () => await requestService.fetch(id),
		enabled: !isNaN(req_id)
	})

	const [attachsCount, setAttachsCount] = useState(0)
	useEffect(() => {
		if (data?.attachs) setAttachsCount(data.attachs)
	}, [data])

	const client = useQuery({
		queryKey: ['client', data?.client],
		queryFn: async () => await clientService.fetch(data?.client ?? 0),
		enabled: !!data?.client
	})

	useEffect(() => {
		if (client.isError) toast.error('Не удалось получить связанного клиента!')
	}, [client.isError])

	return (
		<>
			{isError || (fetchStatus === 'idle' && status === 'pending') ? (
				<Box
					sx={{
						display: 'flex',
						flexDirection: 'column',
						justifyContent: 'center',
						alignItems: 'center'
					}}
					color={'error.main'}
				>
					<SearchX size={100} />
					<Typography
						variant='h6'
						component='div'
						color='textSecondary'
					>
						{isError && !error?.message.includes('404')
							? error?.message
							: 'Заявка не найдена'}
					</Typography>
				</Box>
			) : (
				<>
					{data && (
						<TasksGallery
							for_object={{ id: data.id, name: 'request', count: data.tasks }}
						/>
					)}
					<RequestCard
						request_data={data}
						request_client={
							client && data?.client !== null ? client.data : undefined
						}
					/>
					{data?.client && (
						<Accordion slotProps={{ transition: { mountOnEnter: true } }}>
							<AccordionSummary expandIcon={<ChevronDown />}>
								Связанный клиент (ID #{data.client})
							</AccordionSummary>
							<AccordionDetails>
								{client.isPending ? (
									<Skeleton
										width={250}
										height={120}
									/>
								) : (
									<ClientMinCard client_data={client.data} />
								)}
							</AccordionDetails>
						</Accordion>
					)}
					{data && (
						<Accordion slotProps={{ transition: { mountOnEnter: true } }}>
							<AccordionSummary expandIcon={<ChevronDown />}>
								Вложения ({attachsCount})
							</AccordionSummary>
							<AccordionDetails>
								<AttachGallery
									for_object={{
										id: data.id,
										name: 'request',
										count: data.attachs
									}}
									updateCounter={setAttachsCount}
								/>
							</AccordionDetails>
						</Accordion>
					)}
				</>
			)}

			{/*{data && data.contracts.length > 0 && (*/}
			{/*	<Accordion>*/}
			{/*		<AccordionSummary expandIcon={<ChevronDown />}>*/}
			{/*			Договоры ({data.contracts.length})*/}
			{/*		</AccordionSummary>*/}
			{/*		<AccordionDetails>LL</AccordionDetails>*/}
			{/*	</Accordion>*/}
			{/*)}*/}
			{/*{data && data.order && (*/}
			{/*	<Accordion>*/}
			{/*		<AccordionSummary expandIcon={<ChevronDown />}>*/}
			{/*			Заказ (ID #{data.order})*/}
			{/*		</AccordionSummary>*/}
			{/*		<AccordionDetails>LL</AccordionDetails>*/}
			{/*	</Accordion>*/}
			{/*)}*/}
			{/*<Accordion>*/}
			{/*	<AccordionSummary expandIcon={<ChevronDown />}>*/}
			{/*		Балалалал*/}
			{/*	</AccordionSummary>*/}
			{/*	<AccordionDetails>*/}
			{/*		<ClientMinCard client_data={data} />*/}
			{/*		<ClientMinCard client_data={data} />*/}
			{/*	</AccordionDetails>*/}
			{/*</Accordion>*/}
		</>
	)
}
